package com.le.tester.book.concurrentchallenge.cancelclose;

import java.math.BigInteger;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * createTime：2025-04-02 10:43
 * description：不可靠的取消操作将把生产者阻塞在操作中（不要这么做）
 */
public class BrokenPrimeProducer extends Thread {

    private final BlockingQueue<BigInteger> queue;
    private volatile boolean canceled = false;

    public BrokenPrimeProducer(BlockingQueue<BigInteger> queue) {
        this.queue = queue;
    }


    @Override
    public void run() {
        try {
            BigInteger one = BigInteger.ONE;
            while (!canceled) {
                queue.put(one = one.nextProbablePrime());
            }
        } catch (InterruptedException e) {
            // TODO: 2025-04-02  
        }
    }

    public void cancel() {
        canceled = true;
    }

    void consumerPrime(boolean needMorePrime) {
        BlockingQueue<BigInteger> p = new PriorityBlockingQueue<>();
        BrokenPrimeProducer brokenPrimeProducer = new BrokenPrimeProducer(p);
        brokenPrimeProducer.start();
        try {
            while (needMorePrime) {
                consume(p.take());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            brokenPrimeProducer.cancel();
        }
    }

    private void consume(BigInteger take) {
    }
}
